package commands;

import core.Attribute;

/**
 * Represents a Command to set the value of an attribute.
 */
public class SetAttributeCommand extends Command
{
	/**
	 * Creates a default SetAttributeCommand with null Attribute and value
	 */
	public SetAttributeCommand() {
		this(null, null);
	}

	/**
	 * Creates a new SetAttributeCommand to set the value of an Attribute
	 * @param attribute the Attribute to modify
	 * @param value the value to assign to the Attribute
	 */
	public SetAttributeCommand(Attribute<?> attribute, String value) {
		this.attribute = attribute;
		this.value = value;
	}

	public net.StateUpdate execute() throws CommandException
	{
		if (attribute == null)
			throw new CommandException(this, "Null attribute");
		net.StateUpdate stateUpdate = super.execute();
		stateUpdate.addChange(new net.PropertyChange(attribute, "value", attribute.parseString(value)));
		return stateUpdate;
	}

	public String toString() {
		return "Set attribute " + attribute + " to " + value;
	}

	public Attribute<?> getAttribute() {
		return attribute;
	}

	public void setAttribute(Attribute<?> attribute) {
		this.attribute = attribute;
		oldValue = (attribute == null ? null : (attribute.getValue() == null ? null : attribute.getValue().toString()));
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

	public String getMessage() {
		return "set attribute " + util.Util.prettyPrint(attribute) + " of " + util.Util.prettyPrint(attribute.getParent()) + " from " + oldValue + " to " + value;
	}

	private Attribute<?> attribute;
	private String value, oldValue;
}